/**
 * @file pipes.c
 * @brief
 * @author h0rr0rr_drag0n <h0rr0rr_drag0n@vindekapets.ru
 * @date 15 Июль 2010 22:03:54
 *
 * Functions to work with pipes - open, read and close
 */

#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/stat.h>
#include "define.h"

/**
 * Opening pipe for reading.
 *
 * This func open pipe for reading.
 *
 * @param [in] ppath - path to pipe.
 *
 * @retval pipe descriptor (>=0) on success; negative value on error
 */
int pipe_open(char * ppath) {
    int readffd = 0;

    if ((readffd = open(ppath, O_RDONLY | O_NONBLOCK, 0)) < 0) {
        syslog(LOG_ERR, "Error: open(): cannot open %s: %s", ppath, 
                strerror(errno));
        return -1;
    }

    return readffd;
}

/**
 * Read one char from pipe
 *
 * @param [in] readffd - pipe descriptor
 *
 * @retval readed char in unsigned char, -1 if no readed, -2 on error
 */
int pipe_getchar(int readffd) {
    unsigned char buf = 0;
    int readretval = 0;

    while (readretval <= 0) {
       readretval = read(readffd, &buf, sizeof(unsigned char));

       if (readretval == 0) {
           return -1;
       }
       if (readretval < 0) {
           if (errno == EAGAIN) {
               return -1;
           }
           if (errno == EINTR) {
               continue;
           }
           syslog(LOG_ERR, "Error: read(): %s", strerror(errno));
           return -2;
       } /* if (readretval < 0) */
    } /* while (1) */

    return buf;
}

